package com.itcast.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itcast.constant.MessageConstant;
import com.itcast.constant.RedisMessageConstant;
import com.itcast.entity.Result;
import com.itcast.pojo.Member;
import com.itcast.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RequestMapping("/member")
@RestController
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    //手机快速登录
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response){
        //判断验证码是否输入正确
        String telephone = (String) map.get("telephone");
        //验证码
        String validateCode = (String) map.get("validateCode");
        //获取Redis中的验证码
        String param = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (param !=null && validateCode !=null && param.equals(validateCode)){
            try {
                //登录成功，查询是否为会员
                Member member = memberService.findMember(telephone);
                if (member==null){
                    //该用户不是会员,自动注册会员
                    member = new Member();
                    Date date = new Date();
                    member.setRegTime(date);
                    member.setPhoneNumber(telephone);
                    memberService.add(member);
                }
                //向客户端浏览器写入Cookie
                Cookie cookie = new Cookie("login_member_telephone",telephone);
                cookie.setPath("/");
                cookie.setMaxAge(60*60*24*30);
                response.addCookie(cookie);
                //将会员信息保存到Redis中
                String s = JSON.toJSON(member).toString();
                jedisPool.getResource().setex(telephone,60*30,s);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.ADD_MEMBER_FAIL);
            }

            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            //登录失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
